package chances.epg.commons.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {

	public static final Logger logger = LoggerFactory.getLogger(HttpUtils.class); 
	

	
	



	public static String get(String url,String cookies) {
		String output;
		String result = "";
		try {
			URL aUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) aUrl.openConnection();
			conn.setRequestMethod("GET");
			if(StringUtils.isNotEmpty(cookies)){
				conn.setRequestProperty("Cookie", cookies);
			}
			
			
			conn.setUseCaches(false);
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()), "UTF-8"));
			while ((output = br.readLine()) != null) {
				result += output;
			}
			;
		} catch (Exception e) {
			result = "{}";
			e.printStackTrace();
		} finally {

		}
		return result;

	}
	public static String post(String url,String body) {
		return post(url,body,null);
	}
	public static String post(String url,String body,String cookies) {
		String output;
		StringBuffer resultSb = new StringBuffer();
		BufferedReader br = null;
		try {
			URL aUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) aUrl.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			if(StringUtils.isNotEmpty(cookies)){
				conn.setRequestProperty("Cookie", cookies);
			}
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
			out.write(body);
			out.flush();
			out.close();
			br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			while ((output = br.readLine()) != null) {
				resultSb.append(output);
			}
			conn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

		String result =  resultSb.toString();
		logger.debug("get {} {}",url,result);

		return result;
	}
	
	public static void setCookie(HttpServletResponse response, String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	public static String getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			return "";
		}
		String result = "";
		for (int i = 0; i < cookies.length; i++) {
			String cookieName = cookies[i].getName();
			if (name.equals(cookieName)) {
				result = cookies[i].getValue();
				break;
			}
		}
		return result;
	}

	public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				String cookieName = cookies[i].getName();
				if (name.equals(cookieName)) {
					cookies[i].setMaxAge(0);
					response.addCookie(cookies[i]);
					break;
				}
			}
		}

	}

}
